
package com.softoa.contorller;

import com.softoa.pojo.Document;

import com.softoa.service.IDocumentService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;


import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@CrossOrigin
@RestController
@RequestMapping("/document")
public class DocumentController {
 public String AD;
    @Autowired
    IDocumentService documentService;
    @RequestMapping("upload")
    public String uploadFile(MultipartFile file, HttpServletRequest req){
        if(!file.isEmpty()){
            //获得服务器地址
            String uploadPath = req.getServletContext().getRealPath("/upfiles/");
            System.out.println("上传地址:"+uploadPath);

            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir(); // 如果目录不存在则创建
            }
            String OriginalFilename = file.getOriginalFilename();//获取原文件名    ab.c.txt
            String suffixName = OriginalFilename.substring(OriginalFilename.lastIndexOf("."));//获取原文件后缀名 txt
            //重新随机生成名字
            String filename = UUID.randomUUID().toString() ;
            AD="http://localhost:8080/upfiles/"+filename;
            File serverFile = new File(uploadPath+"\\"+filename);  //根据服务器地址和新的文件名创建的File对象
            try {
                file.transferTo(serverFile); //把上传的文件保存至本地
                /**
                 * 这里应该把filename保存到数据库,供前端访问时使用
                 */
                System.out.println(filename+">>>>>>>>>>>.");
                return filename;//上传成功，返回保存的文件地址
                //这个filename是要存入document库里的documentcontent。

            }catch (IOException e){
                e.printStackTrace();
                System.out.println("上传失败");
                return "";
            }
        }else{
            System.out.println("文件为空");
            return "";
        }
    }

    @RequestMapping("documentcreat")
    public long documentCreat(Document doc ){
        System.out.println(doc.getDocumentClass());

       doc.setDocumentContent(AD);
        documentService.documentInsert(doc);

        //Document doc1=documentService.documentSelectOne(doc);
        return doc.getDocumentId();
    }
    @RequestMapping("documentshow")
    public List<Document> documentsShow(Document doc){
        return documentService.documentSelectList(doc);
    }
    @RequestMapping("documentshow2")
    public List<Document> documentsShow2(Document doc){
        return documentService.documentSelectList2();
    }
}
